package com.yehun.admin.controller;

import com.yehun.admin.models.JsonResult;
import com.yehun.admin.models.PageConfig;
import com.yehun.admin.models.RouteModel;
import com.yehun.entity.PagerEntity;
import com.yehun.entity.Route;
import com.yehun.model.MappingModel;
import com.yehun.service.RouteService;
import com.yehun.utils.MapperUtils;
import com.yehun.utils.PackageUtils;
import com.yehun.utils.ParamUtils;
import com.yehun.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "route")
public class RouteController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(RouteController.class);

    @Autowired
    private RouteService routeService;

    @RequestMapping(value = {"", "index", "list"}, name = "路由列表")
    public String list() {
        return "route/list";
    }

    @ResponseBody
    @RequestMapping(value = "listAjax", name = "路由列表数据")
    public PageConfig<Route> listAjax() {
        int pageIndex = ParamUtils.getPageIndex();
        int pageSize = ParamUtils.getPageSize();
        PagerEntity<Route> pager = routeService.listPager(pageIndex, pageSize);
        return PageConfig.mapper(pager);
    }

    @ResponseBody
    @RequestMapping(value = "add", name = "添加路由")
    public JsonResult add(RouteModel routeModel) {
        JsonResult jsonResult = new JsonResult();
        Route routeEntity = MapperUtils.mapper(routeModel, Route.class);
        int row = routeService.save(routeEntity);
        boolean ret = row > 0;
        jsonResult.setCode(ret ? 0 : 1);
        jsonResult.setMessage(ret ? "success" : "fail");
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping(value = "edit", name = "修改路由")
    public JsonResult edit(RouteModel routeModel) {
        JsonResult jsonResult = new JsonResult();
        Route routeEntity = MapperUtils.mapper(routeModel, Route.class);
        int row = routeService.update(routeEntity);
        boolean ret = row > 0;
        jsonResult.setCode(ret ? 0 : 1);
        jsonResult.setMessage(ret ? "success" : "fail");
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping(value = "getRoutes", name = "获取所有路由")
    public PageConfig<Map<String, Object>> getRoutes() {
        PageConfig<Map<String, Object>> pageConfig = new PageConfig<>();
        List<MappingModel> mappings = PackageUtils.getRequestMappings(BaseController.class);
        if (mappings != null && !mappings.isEmpty()) {
            List<Route> routes = routeService.listAll();
            List<Map<String, Object>> mapList = new LinkedList<>();
            Map<String, Object> map;
            List<Route> routesTmp;
            for (MappingModel mapping : mappings) {
                if (StringUtils.isEmpty(mapping.getName())) continue;
                if (!StringUtils.isEmpty(mapping.getUrl())) {
                    String lastChar = mapping.getUrl().substring(mapping.getUrl().length() - 1, mapping.getUrl().length());
                    if (Objects.equals(lastChar, "/")) {
                        mapping.setUrl(mapping.getUrl().substring(0, mapping.getUrl().length() - 1));
                    } else {
                        mapping.setUrl(mapping.getUrl());
                    }
                }
                final String urlFinal = mapping.getUrl();
                final String pathFinal = mapping.getPath();
                routesTmp = routes.stream().filter(r -> r.getUrl().equals(urlFinal) && r.getPath().equals(pathFinal)).collect(Collectors.toList());
                map = new LinkedHashMap<>();
                map.put("url", urlFinal);
                map.put("path", pathFinal);
                map.put("remark", mapping.getName());
                map.put("flag", (routesTmp != null && !routesTmp.isEmpty()));
                mapList.add(map);
            }
            pageConfig.setTotal(mapList.size());
            pageConfig.setData(mapList);
        }
        return pageConfig;
    }

    @ResponseBody
    @RequestMapping(value = "remove", method = RequestMethod.POST, name = "路由删除")
    public JsonResult remove() {
        Integer[] idArray = ParamUtils.getIntArray("idArray", ",");
        logger.info("idArray={}", idArray.length);
        JsonResult jsonResult = new JsonResult();
        int row = routeService.remove(idArray);
        jsonResult.setCode(row > 0 ? 0 : 0);
        return jsonResult;
    }

}
